
from flask import Blueprint,request,jsonify,make_response,redirect,g
import json
from common.models.User import User
from common.libs.user.UserService import UserService
from common.libs.Helper import ops_render
from application import app,db
from common.libs.UrlManager import UrlManager

route_user = Blueprint('user_page',__name__)

@route_user.route("/login",methods=["GET","POST"])  #GET 做请求  POST做处理
def login():
    if request.method == "GET":
        return ops_render("user/login.html")
    #返回值
    resp = {'code':200,'msg':'登录成功','data':{} }
    #将请求值放到values里来 
    req = request.values
    login_name = req['login_name'] if 'login_name' in req else ''
    login_pwd = req['login_pwd'] if 'login_pwd' in req else ''
    #参数的有效性判断
    if login_name is None or len(login_name) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入正确的用户名"
        return jsonify(resp)
    if login_pwd is None or len(login_pwd) < 1 :
        resp['code'] = -1
        resp['msg'] = "请输入正确的登陆密码"
        return jsonify(resp)

    #flask alchemy查询方法
    user_info = User.query.filter_by( login_name = login_name).first()
    if not user_info:
        resp['code'] = -1
        resp['msg'] = "请输入正确的登陆用户名和密码 -1"
        return jsonify(resp)
    #登录密码的校验  ，用户输入的密码和随机字符串加密
    if user_info.login_pwd != UserService.genePwd(login_pwd,user_info.login_salt):
        resp['code'] = -1
        resp['msg'] = "请输入正确的登陆用户名和密码 -2"
        return jsonify(resp)

    if user_info.status !=1:
        resp['code'] = -1
        resp['msg'] = "您输入的账号有异常,请联系管理员处理"
        return jsonify(resp)

    #用户存在本地的是一个cookik
    response = make_response(json.dumps(resp))
    response.set_cookie(app.config['AUTH_COOKIE_NAME'],"%s#%s"%(UserService.geneAuthCode(user_info),user_info.uid))   #"%s#%s“是对uid的一种加密方式
    return response

@route_user.route("/edit",methods = ["GET","POST"])
def edit():
    if request.method == "GET":
        return ops_render("user/edit.html",{'current':'edit'})
    resp = {'code':200,'msg':'操作成功','data':{}}
    #从request里获取所有的请求值
    req = request.values
    nickname = req['nickname'] if 'nickname' in req else ''
    email = req['email'] if 'email' in req else ''

    if nickname is None or len(nickname) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的姓名~~"
        return jsonify(resp)

    if email is None or len(email) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的邮箱~~"
        return jsonify(resp)

    user_info = g.current_user
    #更新用户名和用户密码
    user_info.nickname = nickname
    user_info.email = email
    #数据库提交
    db.session.add(user_info)
    db.session.commit()
    return jsonify(resp)


@route_user.route("/reset-pwd",methods = ["GET","POST"])
def resetPwd():
    if request.method == "GET":
        return ops_render("user/reset_pwd.html",{'current':'reset-pwd'})
    resp = {'code':200,'msg':'操作成功','data':{}}
    req = request.values
    old_password = req['old_password'] if 'old_password' in req else ''
    new_password = req['new_password'] if 'new_password' in req else ''
    #参数有效性判断
    if old_password is None or len(old_password) < 6:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的原始密码~~"
        return jsonify(resp)
    if new_password is None or len(new_password) < 6:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的新密码~~"
        return jsonify(resp)
    if new_password == old_password:
        resp['code'] = -1
        resp['msg'] = "请重新输入：新密码和原密码不能相同"
        return jsonify(resp)
    #参数校验完后进行密码的更改
    user_info = g.current_user
    user_info.login_pwd = UserService.genePwd(new_password,user_info.login_salt)  #经过加密算法保存密码
    db.session.add(user_info)
    db.session.commit()  #统一提交

    ##通过刷新cookie 里的值来避免每次修改密码之后会重新返回登录界面

    response = make_response(json.dumps(resp))
    response.set_cookie(app.config['AUTH_COOKIE_NAME'],
                        "%s#%s" % (UserService.geneAuthCode(user_info), user_info.uid))  # "%s#%s“是对uid的一种加密方式
    return response


@route_user.route("/logout")
    #将cookie 清空完了以后就退出
def logout():
    #清理cookie 并跳到登录页面
    response = make_response(redirect(UrlManager.buildUrl("/user/login")))
    response.delete_cookie(app.config['AUTH_COOKIE_NAME'])
    return response